<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <view v-if="title === '添加' || types === 'title'">
        <el-form-item v-if="title === '添加'" label="平台账号" prop="accountId">
          <el-select v-model="form.id" value-key="accountPassword">
            <el-option
              v-for="item in accountList"
              :key="item.id"
              :label="item.platformAccount"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="平台账号" prop="accountId">
          <div>{{ form.accountId }}</div>
        </el-form-item>
        <el-form-item label="选题名称" prop="title">
          <el-input v-model.trim="form.title" />
        </el-form-item>
        <el-form-item label="预计完成时间" prop="projectTime">
          <el-date-picker
            v-model="form.projectTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间"
            size="default"
          />
        </el-form-item>
      </view>
      <view
        v-if="title === '编辑' && (types === 'informant' || types === 'info')"
      >
        <el-form-item label="选题内容" prop="details">
          <el-input v-model="form.details" />
        </el-form-item>
        <!--        <el-form-item label="图片" prop="nickname">-->
        <!--          <el-input v-model="form.nickname" />-->
        <!--        </el-form-item>-->
        <el-form-item label="上传图片" prop="pic">
          <el-upload
            :action="action"
            list-type="picture-card"
            :headers="headers"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :show-file-list="false"
            limit="1"
          >
            <el-icon v-if="!form.pic">
              <Plus />
            </el-icon>
            <img
              v-if="form.pic"
              :src="form.pic"
              alt=""
              style="width: 148px; height: 148px"
            />
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="form.pic" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="成本费用" prop="fee">
          <el-input v-model="form.fee" />
        </el-form-item>
        <el-form-item label="实际发布时间" prop="reportTime">
          <el-date-picker
            v-model="form.reportTime"
            format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="请选择时间"
            size="default"
          />
        </el-form-item>
      </view>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    addSelectTopic,
    contentReport,
    editSelectTopic,
    // editTopicRecord,
  } from '@/api/topics'
  import { useUserStore } from '@/store/modules/user'
  import { fetchaccountOperate } from '@/api/accountManagement'
  import { baseURL } from '@/config'

  export default defineComponent({
    name: 'UserManagementEdit',
    props: {
      roles: {
        type: Array,
        default: () => {
          return []
        },
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const userStore = useUserStore()
      const { token } = storeToRefs(userStore)
      const state = reactive({
        formRef: null,
        form: {
          roleIds: [],
        },
        accountList: [],
        types: '',
        currStatus: null,
        headers: {},
        action: '',
        rules: {},
        title: '新增',
        dialogFormVisible: false,
      })
      const fetchAccount = async () => {
        try {
          state.listLoading = true
          const { data: data } = await fetchaccountOperate()
          state.accountList = data
          state.listLoading = false
        } catch (e) {
          console.log(e)
        }
      }
      const showEdit = (row, currStatus, types) => {
        if (!row) {
          state.title = '添加'
        } else {
          state.currStatus = currStatus
          if (types !== undefined) {
            state.types = types
          } else {
            state.types = ''
          }
          state.title = '编辑'
          state.form = JSON.parse(JSON.stringify(row))
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          roles: [],
        }
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            try {
              const form = {}
              console.log(state.form.pic, 'state.form.pic')
              if (state.title === '添加' || state.types === 'title') {
                form.title = state.form.title
                form.projectTime = state.form.projectTime
                console.log(state.form, 'state.form')
                if (state.types === 'title') {
                  form.id = state.form.id
                } else {
                  form.accountId = state.form.id
                }
              } else {
                form.details = state.form.details
                form.pic = state.form.pic
                form.fee = state.form.fee
                form.reportTime = state.form.reportTime
                if (state.form.id) {
                  form.id = state.form.id
                }
              }
              const { msg } =
                state.title === '添加'
                  ? await addSelectTopic(form)
                  : state.types === 'title'
                  ? await editSelectTopic(form)
                  : state.types === 'info'
                  ? await contentReport(form)
                  : state.types === 'informant'
                  ? await contentReport(form)
                  : ''
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (err) {
              console.error(err)
            }
          }
        })
      }
      const handleRemove = (uploadFile, uploadFiles) => {
        console.log(uploadFiles.response)
      }
      const handleSuccess = (uploadFile) => {
        state.form.pic = uploadFile.data.url
        console.log(state.form.imgUrl, 111111)
      }
      onMounted(() => {
        fetchAccount()
        const tokens = JSON.parse(JSON.stringify(token))
        state.headers['Authorization'] = `Bearer ${tokens._object.token}`
        state.action = `${baseURL}/zgyp-system/api/v1/files`
      })
      return {
        ...toRefs(state),
        handleRemove,
        handleSuccess,
        showEdit,
        close,
        save,
      }
    },
  })
</script>
